package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("userMybatisService")  // 指定bean名称，区分内存版本
public class UserMybatisServiceImpl implements UserService {

    private final UserMapper userMapper;

    public UserMybatisServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> findAllUsers() {
        return userMapper.findAll();
    }

    @Override
    public User findUserById(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        return user;
    }

    @Override
    @Transactional
    public User saveUser(User user) {
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            if (userMapper.findById(user.getId()) == null) {
                throw new RuntimeException("用户不存在: " + user.getId());
            }
            userMapper.update(user);
        }
        return user;
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        if (userMapper.findById(id) == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        userMapper.deleteById(id);
    }

    @Override
    public List<User> findUsersByName(String name) {
        return userMapper.findByName(name);
    }

    @Override
    public boolean isEmailExists(String email, Long excludeId) {
        return userMapper.countByEmail(email, excludeId != null ? excludeId : -1L) > 0;
    }
} 